package com.alliky.core.pay;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alliky.core.config.Config;
import com.alliky.core.log.KLog;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

import es.dmoral.toasty.Toasty;

public class PayUtil {

    private static final String TAG = PayUtil.class.getSimpleName();

    private static final int SDK_PAY_FLAG = 0x01;

    public static PayUtil getInstance() {
        return Holder.INSTANCE;
    }

    private static class Holder {
        private static PayUtil INSTANCE = new PayUtil();
    }

    private IWXAPI getWXApi(Activity context) {
        IWXAPI api = WXAPIFactory.createWXAPI(context, Config.getWechatAppId());
        api.registerApp(Config.getWechatAppId());
        return api;
    }

    public void sendWeChatPay(Activity context, PayInfo payInfo) {
        doWechatPay(context, payInfo);
    }

    public void sendAlipay(Activity context, String orderInfo) {
        doAliPay(context, orderInfo);
    }

    private void doWechatPay(Activity context, PayInfo payInfo) {
        //result中是重服务器请求到的签名后各个字符串，可自定义
        //result是服务器返回结果
        PayReq request = new PayReq();
        request.appId = payInfo.getAppid();
        request.partnerId = payInfo.getPartnerid();
        request.prepayId = payInfo.getPrepayid();
        request.packageValue = payInfo.getPackageX();
        request.nonceStr = payInfo.getNoncestr();
        request.timeStamp = payInfo.getTimestamp();
        request.sign = payInfo.getSign();
        boolean send = getWXApi(context).sendReq(request);
    }

    /**
     * @param context   上下文
     * @param orderInfo 签名后定订单
     */
    private static void doAliPay(Activity context, String orderInfo) {

        // result中是重服务器请求到的签名后字符串,赋值，此处随便写的
        // final String orderInfo = "app_id=2015052600090779&biz_content=%7B%22timeout_express%22%3A%2230m%22%2C%22seller_id%22%3A%22%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22total_amount%22%3A%220.02%22%2C%22subject%22%3A%221%22%2C%22body%22%3A%22%E6%88%91%E6%98%AF%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%22%2C%22out_trade_no%22%3A%22314VYGIAGG7ZOYY%22%7D&charset=utf-8&method=alipay.trade.app.pay&sign_type=RSA2&timestamp=2016-08-15%2012%3A12%3A15&version=1.0&sign=MsbylYkCzlfYLy9PeRwUUIg9nZPeN9SfXPNavUCroGKR5Kqvx0nEnd3eRmKxJuthNUx4ERCXe552EV9PfwexqW%2B1wbKOdYtDIb4%2B7PL3Pc94RZL0zKaWcaY3tSL89%2FuAVUsQuFqEJdhIukuKygrXucvejOUgTCfoUdwTi7z%2BZzQ%3D";   // 订单信息
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
//                PayTask alipay = new PayTask(context);
//                Map<String, String> result = alipay.payV2(orderInfo, true);
//                Message msg = new Message();
//                msg.what = SDK_PAY_FLAG;
//                msg.obj = result;
//                mHandler.sendMessage(msg);
//
//                KLog.d(TAG, "aliresult--->" + result);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 支付宝状态
     * 9000 订单支付成功
     * 8000 正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
     * 4000 订单支付失败
     * 5000 重复请求
     * 6001 用户中途取消
     * 6002 网络连接出错
     * 6004 支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
     * 其它   其它支付错误
     */
    private static Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        showSuccessMessage("支付成功");
                        PayListenerUtil.getInstance().addSuccess();
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        showMessage("取消支付");
                        PayListenerUtil.getInstance().addCancel();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showErrorMessage("支付失败");
                        PayListenerUtil.getInstance().addError();
                    }
                    break;
                }
            }
        }
    };

    private static void showMessage(String message) {
        Toasty.normal(Config.getApplicationContext(), message).show();
    }

    private static void showSuccessMessage(String message) {
        Toasty.success(Config.getApplicationContext(), message).show();
    }

    private static void showErrorMessage(String message) {
        Toasty.error(Config.getApplicationContext(), message).show();
    }
}
